import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import api from '../utils/api';

const useAuthStore = create(
  persist(
    (set) => ({
      // 状态
      user: null,
      token: null,
      isAuthenticated: false,
      loading: false,
      error: null,

      // 登录
      login: async (credentials) => {
        set({ loading: true, error: null });
        try {
          const response = await api.login(credentials);
          const { user, token } = response.data;
          
          set({
            user,
            token,
            isAuthenticated: true,
            loading: false,
            error: null,
          });
          
          localStorage.setItem('token', token);
          localStorage.setItem('user', JSON.stringify(user));
          
          return response;
        } catch (error) {
          set({
            loading: false,
            error: error.response?.data?.message || '登录失败',
          });
          throw error;
        }
      },

      // 注册
      register: async (userData) => {
        set({ loading: true, error: null });
        try {
          const response = await api.register(userData);
          const { user, token } = response.data;
          
          set({
            user,
            token,
            isAuthenticated: true,
            loading: false,
            error: null,
          });
          
          localStorage.setItem('token', token);
          localStorage.setItem('user', JSON.stringify(user));
          
          return response;
        } catch (error) {
          set({
            loading: false,
            error: error.response?.data?.message || '注册失败',
          });
          throw error;
        }
      },

      // 获取用户信息
      getProfile: async () => {
        try {
          const response = await api.getProfile();
          const user = response.data;
          
          set({
            user,
            isAuthenticated: true,
          });
          
          localStorage.setItem('user', JSON.stringify(user));
          
          return response;
        } catch (error) {
          set({
            isAuthenticated: false,
            user: null,
          });
          throw error;
        }
      },

      // 更新用户信息
      updateProfile: async (userData) => {
        try {
          const response = await api.updateProfile(userData);
          const user = response.data;
          
          set({
            user,
          });
          
          localStorage.setItem('user', JSON.stringify(user));
          
          return response;
        } catch (error) {
          set({
            error: error.response?.data?.message || '更新失败',
          });
          throw error;
        }
      },

      // 退出登录
      logout: async () => {
        try {
          await api.logout();
        } catch (error) {
          console.error('Logout error:', error);
        } finally {
          set({
            user: null,
            token: null,
            isAuthenticated: false,
            loading: false,
            error: null,
          });
          
          localStorage.removeItem('token');
          localStorage.removeItem('user');
        }
      },

      // 清除错误
      clearError: () => {
        set({ error: null });
      },

      // 初始化认证状态
      initAuth: () => {
        const token = localStorage.getItem('token');
        const user = localStorage.getItem('user');
        
        if (token && user) {
          try {
            const userData = JSON.parse(user);
            set({
              user: userData,
              token,
              isAuthenticated: true,
            });
          } catch (error) {
            console.error('Failed to parse user data:', error);
            localStorage.removeItem('token');
            localStorage.removeItem('user');
          }
        }
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);

export default useAuthStore; 